using AppToolKit.Core.AttributeDiscovery;
using AppToolKit.Core.Context.Spring.Register;
using AppToolKit.Core.Logging;
using Common.Logging;
using Spring.Context;
using Spring.Objects.Factory.Support;
using System;
using System.Diagnostics;
using System.Reflection;
namespace AppToolKit.Core.Context.Spring
{
	public class ContextFixtureAttributeProcessor : IFeatureProcessor, IApplicationContextAware
	{
		private static ILog logger_ = LogManager.GetLogger(DefaultLogger.LOGGER_NAME);
		private ContextRegisterManager registerMgr_;
		private IApplicationContext context_;
		public IApplicationContext ApplicationContext
		{
			get
			{
				return this.context_;
			}
			set
			{
				Debug.Assert(value != null);
				this.context_ = value;
				this.registerMgr_ = new ContextRegisterManager(value);
			}
		}
		public bool IsSupport(Assembly assembly)
		{
			return assembly.IsDefined(typeof(AssemblyNeedDetectAttribute), true);
		}
		public void Process(Type type, FeatureProcessContext ctx)
		{
			if (ContextFixtureAttributeProcessor.logger_.IsDebugEnabled)
			{
				ContextFixtureAttributeProcessor.logger_.Debug(string.Format("Check ContextFixture ", type));
			}
			if (type.IsDefined(typeof(ContextFixtureAttribute), false))
			{
				if (ContextFixtureAttributeProcessor.logger_.IsDebugEnabled)
				{
					ContextFixtureAttributeProcessor.logger_.Debug(string.Format("ContextFixture Process({0})", type));
				}
				ContextFixtureAttribute contextFixtureAttribute = (ContextFixtureAttribute)type.GetCustomAttributes(typeof(ContextFixtureAttribute), false)[0];
				RootObjectDefinition rootObjectDefinition = this.registerMgr_.CreateDefine(type);
				rootObjectDefinition.IsSingleton=contextFixtureAttribute.Singleton;
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
				MethodInfo[] array = methods;
				for (int i = 0; i < array.Length; i++)
				{
					MethodInfo methodInfo = array[i];
					if (methodInfo.IsDefined(typeof(InitMethodAttribute), false))
					{
                        rootObjectDefinition.InitMethodName=methodInfo.Name;
					}
					if (methodInfo.IsDefined(typeof(DestroyMethodAttribute), false))
					{
						rootObjectDefinition.DestroyMethodName=methodInfo.Name;
					}
				}
				string objName = string.Empty;
				if (string.IsNullOrEmpty(contextFixtureAttribute.Name))
				{
					objName = this.registerMgr_.GeneratRegisterName(type);
				}
				else
				{
					objName = contextFixtureAttribute.Name;
				}
				this.registerMgr_.Register(objName, rootObjectDefinition);
                if (rootObjectDefinition.IsSingleton && !string.IsNullOrEmpty(rootObjectDefinition.InitMethodName))
				{
					ctx.InitialUnit.Add(new InitUnitTemplate(delegate
					{
						this.registerMgr_.InitObject(objName);
					}
					));
				}
			}
		}
		public void ProcessAssembly(Assembly assembly)
		{
		}
	}
}
